package com.example.menuvirtualclient.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.Toast;

import com.example.menuvirtualclient.core.Comment;
import com.example.menuvirtualclient.core.Dish;
import com.example.menuvirtualclient.core.Order;
import com.example.menuvirtualclient.core.OrderDetail;
import com.example.menuvirtualclient.repository.CommentRepository;
import com.example.menuvirtualclient.repository.DishRepository;

public class Common {

	public static String IP = "192.168.0.14";
	public static String URL_WS = "http://"+IP+":8080/menuvirtualws/services/OperatorClass/";
//	public static String URL_WS = "http://"+IP+":1313/menuvirtualws/services/OperatorClass/";
	public static String URL_IMAGES = "http://"+IP+":8080/MenuVirtualServer/uploaded/";

//	public static String URL_WS = "http://192.168.43.45:1313/menuvirtualws/services/OperatorClass/";
//	public static String URL_IMAGES = "http://192.168.43.45:8080/MenuVirtualServer/uploaded/";

	
	@SuppressWarnings("finally")
	public static byte[] ConvertImageToByteArray(String selectedImagePath)
			throws IOException {
		byte[] byteImage = null;
		try {

			FileInputStream instream = new FileInputStream(selectedImagePath);
			BufferedInputStream buffer = new BufferedInputStream(instream);
			byteImage = new byte[buffer.available()];
			buffer.read(byteImage);
		} catch (IOException ex) {
			Log.e("Common", ex.getMessage());
			throw ex;
		} finally {
			return byteImage;
		}
	}

	/*
	 * public static byte[] getfdf(R.drawable image){ BitmapDrawable bmd =
	 * (BitmapDrawable) getResources().getDrawable(image); Bitmap bm =
	 * bmd.getBitmap(); ByteBuffer byteBuff = ByteBuffer.allocate(bm.getWidth()
	 * * bm.getHeight() * 4); byteBuff.rewind();
	 * bm.copyPixelsToBuffer(byteBuff); byte[] tmp = new byte[bm.getWidth() *
	 * bm.getHeight() * 4]; byteBuff.rewind(); byteBuff.get(tmp);
	 * 
	 * return tmp; }
	 */

	public static byte[] Encode(Bitmap icon) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		icon.compress(Bitmap.CompressFormat.PNG, 50, baos);
		byte[] data = baos.toByteArray();
		// String test = Base64.encodeBytes(data);
		// return test;
		return data;
	}

	public static double Round(double value) {
		DecimalFormat twoDForm = new DecimalFormat("####.##");
		return Double.valueOf(twoDForm.format(value));
	}

	public static float Round(float d, int decimalPlace) {
		BigDecimal bd = new BigDecimal(Float.toString(d));
		bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
		return bd.floatValue();
	}

	public static double Round(double value, int decimalPlace) {
		double p = (double) Math.pow(10, decimalPlace);
		value = value * p;
		double tmp = Math.round(value);
		return (double) tmp / p;
	}

	public static void ShowToast(Context context, String message) {
		Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
		toast.show();
	}

	// metodo para guarda la foto de la orden
	public static String encodeOrder(Order order) {
		StringBuilder result = new StringBuilder();
		result.append(order.getId()).append(",").append(order.getStatus())
				.append("[");
		// 0 - DetailId
		// 1 - DishId
		// 2 - Status
		// 3 - CookingPoint
		// 4 - Size
		// 5 - Comment
		// 6 - Detail Type
		for (OrderDetail detail : order.getOrderDetails()) {
			// if (detail.getStatus() == -1) {
			result.append(detail.getId()).append(",")
					.append(detail.getDish().getId()).append(",")
					.append(detail.getStatus()).append(",")
					.append(detail.getCookingPoint()).append(",");
			if (detail.getDish().getSize().equals("Normal")) {
				result.append(1).append(",");
			} else if (detail.getDish().getSize().equals("Chica")) {
				result.append(2).append(",");
			} else if (detail.getDish().getSize().equals("Grande")) {
				result.append(3).append(",");
			}
			result.append(detail.getComment().replace(",","").replace(".", "")).append(",")
			.append(detail.getDetail_type()).append(",");
			
			if (detail.getComments() != null) {
				for (Comment oc : detail.getComments()) {
					if (oc != null) {
						result.append(oc.getId()).append(".");
					}
				}
			}
			result.append("|");
			// }
		}
		return result.toString();
	}

	// metodo para enviar la orden al server codificada, reemplaza el estado por
	// el cooking point
	public static String encodeOrderActive(Order order) {
		StringBuilder result = new StringBuilder();
		result.append(order.getId()).append(",").append(order.getStatus())
				.append("[");
		// 0 - DetailId
		// 1 - DishId
		// 2 - Status
		// 3 - CookingPoint
		// 4 - Size
		// 5 - Comment
		// 6 - Detail Type
		try {
			for (OrderDetail detail : order.getOrderDetails()) {
				if (detail.getStatus() == -1) {
					result.append(detail.getId()).append(",")
							.append(detail.getDish().getId()).append(",")
							.append(detail.getStatus()).append(",")
							.append(detail.getCookingPoint()).append(",");
					if (detail.getDish().getSize().equals("Normal")) {
						result.append(1).append(",");
					} else if (detail.getDish().getSize().equals("Chica")) {
						result.append(2).append(",");
					} else if (detail.getDish().getSize().equals("Grande")) {
						result.append(3).append(",");
					}
					result.append(detail.getComment().replace(",","").replace(".", "")).append(",")
					.append(detail.getDetail_type()).append(",");

					if (detail.getComments() != null) {
						for (Comment oc : detail.getComments()) {
							result.append(oc.getId()).append(".");
						}
					}
					result.append("|");
				}
			}
		} catch (Exception e) {
			return "";
		}
		
		return result.toString();
	}

	// decodifica la orden desde el server y la foto (el server no env�a
	public static Order decodeOrder(String response, Context context) {
		final CommentRepository commentRepository = new CommentRepository(
				context);
		final DishRepository dishRepository = new DishRepository(context);
		Order order = null;
		List<OrderDetail> ods = new ArrayList<OrderDetail>();
		if (response != null) {

			// 1,1[1,6,1,5.5.|2,5,1,|3,1,0,4.|4,2,1,3.1.|
			// 1,1[1,1,-1,1.2.|2,2,-1,2.|
			order = new Order();

			order.setId(Integer.valueOf(response.split("\\[")[0].split(",")[0]));
			order.setStatus(Integer.valueOf(response.split("\\[")[0].split(",")[1]));

			if (response.split("\\[").length > 1) {
				String[] details = response.split("\\[")[1].split("\\|");

				for (String detail : details) {
					OrderDetail od = new OrderDetail();
					od.setId(Integer.valueOf(detail.split(",")[0]));
					Dish d = new Dish();
					long idDish = Long.valueOf(detail.split(",")[1]);
					d = dishRepository.Get(idDish);
					od.setDish(d);
					int dStatus = Integer.valueOf(detail.split("\\,")[2]);
					int dCookingPoint = Integer.valueOf(detail.split("\\,")[3]);
					int dSize = Integer.valueOf(detail.split("\\,")[4]);
					String dComment = detail.split("\\,")[5];
					int dDetail_Type = Integer.valueOf(detail.split("\\,")[6]);

					od.setStatus(dStatus);
					od.setCookingPoint(dCookingPoint);
					od.setComment(dComment);
					od.setDetail_type(dDetail_Type);
					
					if (dSize == 1) {
						od.getDish().setSize("Normal");
					} else if (dSize == 2) {
						od.getDish().setSize("Chica");
					} else if (dSize == 3) {
						od.getDish().setSize("Grande");
					}

					if (detail.split("\\,").length > 7) {
						String[] comments = detail.split("\\,")[7].split("\\.");

						if (comments.length > 0) {
							List<Comment> cos = new ArrayList<Comment>();
							for (String comment : comments) {
								Comment co = new Comment();
								co = commentRepository.Get(Integer
										.valueOf(comment));
								cos.add(co);
							}
							od.setComments(cos);
						}
					} else {
						List<Comment> cos = new ArrayList<Comment>();
						od.setComments(cos);
					}
					ods.add(od);

					Log.i("Mensaje", "Id:" + 1 + " - Status:" + 1);
				}
			}
		}
		order.setOrderDetails(ods);
		return order;
	}
}
